<?php


namespace App\Api\Hmyl;

use PhalApi\Api;
use PhalApi\Exception\BadRequestException;

/**
 * 韩美医疗backReserve
 *
 * @author: dogstar <chanzonghuang@gmail.com> 2014-10-04
 */
class Back extends Api
{

    public function getRules()
    {
        return array(
            'backReserve' => array(),
            'backCheckResult' => array(),
            'backFile' => array(),
        );
    }



    /**
     * sendbackResult
     */
    public function sendbackResult($taskId)
    {
        //新写一个接口用来发送
        $itemlist = \PhalApi\DI()->notorm->zhjlgetworklist->where('taskId', $taskId)->fetchAll();

        // return $itemlist;

        foreach ($itemlist as $key => $value) {
            $itemlist[$key]['state'] = $value['state']? $value['state']: 1; //1:合格 2:不合格 3:取消检测
            $itemlist[$key]['outCode'] = $value['enddh'] ? $value['enddh'] : 'out-123456';
        }

        // return $itemlist;

        $clientId = '1836613531034755074';
        $secret = 'ee0230ce26ef98db026cf1732097959f';
        $url = 'https://meas.bjhanmi.com.cn/prod-api/external/backCheckResult';
        // $url = 'https://meas.hanmiit.com.cn/prod-api/external/backCheckResult';

        $timestamp = date("Y-m-d H:i:s", time());
        $str = $clientId . $secret . $timestamp;
        $sign = md5($str);

        // 先实例
        $curl = new \PhalApi\CUrl();
        $curl->setHeader(array('Content-Type' => 'application/json'));

        $data = array(
            'clientId' => $clientId,
            'timestamp' => $timestamp,
            'sign' => $sign,
            'itemMeterList' => $itemlist,
        );

        $rs = $curl->post($url, json_encode($data), 3000);
        $rs = json_decode($rs, true);

        if ($rs['code'] == 0) {
            $curl = new \PhalApi\CUrl();
            // 设置请求URL
            $url = "https://api.wenfree.cn/?s=App.Notice.Dingding&content=【韩美推送结果一次】";
            // 发送GET请求，超时时间设置为3000毫秒
            $curl->get($url, 3000);
            \PhalApi\DI()->notorm->zhjlgetworklist->where(array('taskId' => $taskId))->update(array('backResult' => '1'));
        }
        return array( '原始数据' => $data, '发送数据' => json_encode($data), "韩美" => $rs);
    }


    /**
     * backCheckResult 
     */
    public function backCheckResult()
    {
        //此接口用来同步泽恒过来的结果
        $item = \PhalApi\DI()->notorm->zhjlgetworklist->where(array('backResult' => array(null, 0), 'todo' => '1'))->order('id asc')->fetchOne();

        if (!$item) {
            throw new BadRequestException('没有需要返回的设备信息');
        }

        // return $item;

        $url = 'https://26er314622.goho.co/?s=App.ZhjlDoneDH.getdh';
        $postData = array(
            "page" => 1,
            "size" => 10,
            "username" => "A003918",
            "where" => json_encode(array("lqsj" => $item['dh']))
        );

        // 先实例
        $curl = new \PhalApi\CUrl();
        $rs = $curl->post($url, json_encode($postData), 30000);
        $rs = json_decode($rs, true);

        //这里读出了完工单号
        // return $rs;

        if ($rs['data']['count'] > 0) {
            \PhalApi\DI()->notorm->zhjlgetworklist->where(array('taskId' => $item['taskId']))->update(array('enddh' => $rs['data']['data'][0]['dh']));
            // return $rs['data'];
            $url = 'https://26er314622.goho.co/?s=App.ZhjlDoneDH.getdhsb';
            $postData = array(
                "dh" => $item['enddh']
            );
            $curl->setHeader(array('Content-Type' => 'application/json'));
            $rs = $curl->post($url, json_encode($postData), 30000);
            $rs = json_decode($rs, true);

            $itemlist = $rs['data'];
            
            $has_url = false;
            
            if ($rs['data']) {
                foreach ($rs['data'] as $key => $value) {
                    $price = number_format((floatval($value['jdf1']) + floatval($value['qtfy'])), 2, '.', '');
                    // 将 $value['jcrq'] 从 20250507 格式转换为 2025-05-07 格式
                    $formattedDate = substr($value['jcrq'], 0, 4) . '-' . substr($value['jcrq'], 4, 2) . '-' . substr($value['jcrq'], 6, 2);
                    $itemUpdate = array(
                        'itemNo' => $value['jtwz'],
                        'url' => $value['url'],
                        'checkDate' => $formattedDate,
                        'zslb' => $value['zslb'],
                        'certificateNo' => $value["tbpdjg"],
                        "price" => $price,
                        'update_time' => date('Y-m-d H:i:s', time()),
                        'Result' => $value['zslb'] == 99 ? '3' : ($value['zslb'] == 23 ? '2' : '1'),
                        'state' => $value['zslb'] == 99 ? '3' : ($value['zslb'] == 23 ? '2' : '1')
                    );
                    if( $value['url'] ){
                        \PhalApi\DI()->notorm->zhjlgetworklist->where(array('itemNo' => $value['jtwz']))->update($itemUpdate);
                        $has_url = true;
                        
                    }else{
                        $curl = new \PhalApi\CUrl();
                        // 设置请求URL
                        $url = "https://api.wenfree.cn/?s=App.Notice.Dingding&content=【" .$value['jtwz'] ."有结果，无证书】";
                        // 发送GET请求，超时时间设置为3000毫秒
                        // $curl->get($url, 3000);
                        $has_url = false;
                    }
                    // return $itemUpdate;
                }
                if( $has_url ){
                    $send = $this->sendbackResult($item['taskId']);
                }
                // return $itemlist;
                return [$rs['data'], $send];
            }
        }

        return ['还没有完工单号', $rs];
    }


    


    /**
     * backReserve
     */

    public function backReserve()
    {
        $item_ = \PhalApi\DI()->notorm->zhjlgetworklist->where(array('backinfo' => '0'))->fetchOne();

        if (!$item_) {
            throw new BadRequestException('没有需要返回的设备信息');
        }


        $items = \PhalApi\DI()->notorm->zhjlgetworklist->where(array('taskId' => $item_['taskId']))->fetchAll();

        foreach ($items as $key => $item) {
            $items[$key]['number'] = $items['number'] ? $item['number'] : 1;
            $items[$key]['outCode'] = $items['dh'] ? $item['dh'] : '123456';
            $items[$key]['state'] = 1;
            $items[$key]['checkDate'] = $items['checkDate'];
        }


        $clientId = '1836613531034755074';
        $secret = 'ee0230ce26ef98db026cf1732097959f';
        $url = 'https://meas.bjhanmi.com.cn/prod-api/external/backReserve';
        // $url = 'https://meas.hanmiit.com.cn/prod-api/external/backReserve';

        $timestamp = date("Y-m-d H:i:s", time());
        $str = $clientId . $secret . $timestamp;
        $sign = md5($str);

        // 先实例
        $curl = new \PhalApi\CUrl();
        $curl->setHeader(array('Content-Type' => 'application/json'));

        $data = array(
            'clientId' => $clientId,
            'timestamp' => $timestamp,
            'sign' => $sign,
            'itemMeterList' => $items
        );

        //  return $data;

        $rs = $curl->post($url, json_encode($data), 3000);
        $rs = json_decode($rs, true);

        if ($rs['code'] == 0) {
            \PhalApi\DI()->notorm->zhjlgetworklist->where(array('taskId' => $item_['taskId']))->update(array('backinfo' => '1'));
        }
        return $rs;
    }



    /**
     * backFile
     */

    public function backFile()
    {
        // $item = \PhalApi\DI()->notorm->zhjlgetworklist->where(array('backzs' => '0', "Result" => '1'))->fetchOne();
        
        // 由于需要推送不合格的itemNo所以全部取出来
        $item = \PhalApi\DI()->notorm->zhjlgetworklist->where(array('backzs' => '0', 'backResult' => '1'))->fetchOne();
        
        if (!$item) {
            throw new BadRequestException('没有需要返回的设备信息');
        }

        $send = $this->sendbackResult($item['taskId']);

        $itemlist = \PhalApi\DI()->notorm->zhjlgetworklist->where(
            array(
                'taskId' => $item['taskId'],
                'backzs' => '0',
                'state' => array(1,2),
                'url like ?' => 'http%',
            )
        )->fetchAll();

        $itemIds = array_column($itemlist, 'id');

        if (!$itemlist) {
            throw new BadRequestException('没有需要返回的设备信息');
        }

        foreach ($itemlist as $key => $value) {
            $itemlist[$key]['fileType'] = $value['Result'] ? $value['Result'] : '3';
            $itemlist[$key]['price'] = $value['price'] ? $value['price'] : '150.00';
            $itemlist[$key]['outCode'] = $value['enddh'] ? $value['enddh'] : 'ZHJL-HM-' . $value['itemNo'];
            $itemlist[$key]['certificateNo'] = $value['certificateNo'] ? $value['certificateNo'] : 'ZHJL-HM-' . $value['itemNo'];
            $itemlist[$key]['file'] = $value['url'] ? $value['url'] : '';
        }

        // return $itemlist;
        $clientId = '1836613531034755074';
        $secret = 'ee0230ce26ef98db026cf1732097959f';
        $url = 'https://meas.bjhanmi.com.cn/prod-api/external/backFile';
        // $url = 'https://meas.hanmiit.com.cn/prod-api/external/backFile';

        $timestamp = date("Y-m-d H:i:s", time());
        $str = $clientId . $secret . $timestamp;
        $sign = md5($str);

        // 先实例
        $curl = new \PhalApi\CUrl();
        $curl->setHeader(array('Content-Type' => 'application/json'));

        $data = array(
            'clientId' => $clientId,
            'timestamp' => $timestamp,
            'sign' => $sign,
            'itemMeterList' => $itemlist,
        );

        $rs = $curl->post($url, json_encode($data), 3000);
        $rs = json_decode($rs, true);

        if ($rs['code'] == 0) {
            $curl = new \PhalApi\CUrl();
            // 设置请求URL
            $url = "https://api.wenfree.cn/?s=App.Notice.Dingding&content=【韩美上传证书一次】";
            // 发送GET请求，超时时间设置为3000毫秒
            $curl->get($url, 3000);
            \PhalApi\DI()->notorm->zhjlgetworklist->where(array('id' => $itemIds))->update(array('backzs' => '1'));
        }
        return [$data, json_encode($data), $rs];
    }

}
